package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:ahang
 * @create:2022-07-19 15:02
 * @Description:
 */

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;

    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }


    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Map<String, List<Role>> findRolesByAdminId(Long id) {
        //查询所有元素
        List<Role> roleList = roleDao.findAll();
        //查询已经拥有的角色id
        List<Long> roleIds = adminRoleDao.findRoleIdsByAdminId(id);
        
        //对角色进行分类
        List<Role> noAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList = new ArrayList<>();

        for (Role role : roleList) {
            //已经分配
            if(roleIds.contains(role.getId())){
                assignRoleList.add(role);
            }else{
                noAssignRoleList.add(role);
            }
        }

        Map<String, List<Role>> roleMap = new HashMap<>();
        roleMap.put("assignRoleList",assignRoleList);
        roleMap.put("noAssignRoleList",noAssignRoleList);
        return roleMap;
        }

    /**
     * 根据用户分配权限
     * @param adminId
     * @param roleIds
     */
    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
        //删除原有的权限
        adminRoleDao.deleteByAdminId(adminId);

        //添加现在导入的权限
        for (Long roleId : roleIds) {
            //前端传的是字符串进行解析之后会有空字符串
            if(StringUtils.isEmpty(roleId)) continue;
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            adminRoleDao.insert(adminRole);
        }
    }
}



